<template>
  <div ref="container">
    <div
      class="get_more_coupon"
      @click="getMoreCoupon"
      v-if="(withPhone && couponsList.length == 0) || !withPhone"
    >
      <img
        src="../../../assets/images/coupon/coupon_center.png"
        alt=""
        class="img"
      />
    </div>
    <div class="coupon-list" v-if="couponsList.length > 0">
      <div
        class="item acea-row bg2"
        :class="{
          bg1: item.type == 1,
          is_used: item.status == 2 || item.status == 3
        }"
        v-cloak
        v-for="(item, index) in couponsList"
        :key="index"
      >
        <div class="money" :class="item._type === 0 ? 'moneyGray' : ''">
          <div>
            ￥<span class="num">{{ item.coupon_price }}</span>
          </div>
          <div class="pic-num">满{{ item.use_min_price }}元可用</div>
          <div class="pic-num">{{ formatDec(item.dec) }}</div>
          <div
            class="dec_info"
            v-if="item.dec.length > 7"
            @click="item.showInfo = !item.showInfo"
          >
            详细信息
          </div>
          <CouponDecWindow :decInfo="item.showInfo" :detail="item.dec" />
        </div>
        <div class="text">
          <div class="condition">
            <span class="line-title">{{ item.title }}</span>
          </div>
          <div class="coupon_time">
            <div v-if="!withPhone">
              <span v-if="item.time_type == 1">{{ item.time }}</span>
              <span v-else>领取后{{ item.time }}天有效</span>
            </div>
            <span v-else>{{ item.time }}天后到期</span>
          </div>
          <div class="data acea-row row-between-wrapper">
            <div v-if="!withPhone">
              <div class="bnt" v-if="item.status == 1" @click="toUse(item)">
                立即使用
              </div>
              <div class="bnt" v-else-if="item.status == 2">已使用</div>
              <div class="bnt" v-else-if="item.status == 3">已过期</div>
            </div>
            <div v-else class="bnt" @click="toUse(item)">去购物</div>
          </div>
        </div>
      </div>
    </div>
    <!--暂无优惠券-->
    <div class="noCommodity" v-if="couponsList.length === 0">
      <div class="noPictrue">
        <img
          v-if="!withPhone"
          src="@assets/images/noCoupon.png"
          class="image"
        />
        <span
          class="text"
          v-else-if="withPhone && $route.query.success == 'false'"
          >{{ $route.query.msg }}</span
        >
      </div>
    </div>
  </div>
</template>
<script>
import { getCouponsUser, getCoupon } from "@api/user";
import CouponDecWindow from "@components/couponDecWindow";
const NAME = "UserCoupon";
import shareMsg from "../../../assets/js/common/shareConfig.js";
import cookie from "@utils/store/cookie";
export default {
  name: "UserCoupon",
  components: { CouponDecWindow },
  props: {},
  data: function() {
    return {
      couponsList: [],
      loading: false,
      withPhone: ""
    };
  },
  watch: {
    $route(n) {
      this.withPhone = cookie.get("withPhone");
      if (n.name == NAME) {
        this.couponsList = [];
        if (n.query.from1 == "app") {
          let that = this;
          this.getParameter();
          window["onWebResponse"] = str => {
            that.onWebResponse(str);
          };
        } else {
          this.withPhone ? this.getUseCouponsWithPhone() : this.getUseCoupons();
        }
        // document.addEventListener(
        //   "WeixinJSBridgeReady",
        //   function onBridgeReady() {
        //     // 通过下面这个API隐藏右上角按钮
        //     WeixinJSBridge.call("hideOptionMenu");
        //   }
        // );
      } else {
        cookie.set("withPhone", "");
        // document.addEventListener(
        //   "WeixinJSBridgeReady",
        //   function onBridgeReady() {
        //     // 通过下面这个API显示右上角按钮
        //     WeixinJSBridge.call("showOptionMenu");
        //   }
        // );
      }
    }
  },
  created() {
    this.withPhone = cookie.get("withPhone");
    const { ds_token = "" } = this.$route.query;
    if (ds_token) {
      this.$store.commit("LOGIN", ds_token);
    }
  },
  mounted() {
    let that = this;
    if (this.$route.query.from1 == "app") {
      shareMsg.shareConfig("app", "0", "0", "", "", "", "", "", "0");
      this.getParameter();
      window["onWebResponse"] = str => {
        that.onWebResponse(str);
      };
    } else {
      this.withPhone ? this.getUseCouponsWithPhone() : this.getUseCoupons();
    }
    // document.addEventListener("WeixinJSBridgeReady", function onBridgeReady() {
    //   // 通过下面这个API隐藏右上角按钮
    //   WeixinJSBridge.call("hideOptionMenu");
    // });
  },
  destroyed() {
    cookie.set("withPhone", "");
  },
  methods: {
    getUseCouponsWithPhone: function() {
      if (this.$route.query.success == "false") return;
      let that = this;
      let ids = this.withPhone;
      let q = {
        page: 0,
        issue_coupon_ids: ids ? [ids] : undefined
      };
      getCoupon(q).then(res => {
        that.loading = false;
        this.couponsList = res.data.map(item => {
          return {
            ...item,
            showInfo: false
          };
        });
      });
    },
    formatDec(text) {
      return text.length > 7 ? `${text.slice(0, 7)}...可用` : text;
    },
    // 获取app登录状态
    onWebResponse: function(str) {
      var obj = JSON.parse(str);
      var action = obj.action;
      var content = obj.content;
      if (action == "setUserInfo") {
        let isToken = content.ds_token;
        // let expires_time = content.ds_expires_time;
        // let isSalt = content.salt;
        this.$store.commit("LOGIN", isToken);
        this.$nextTick(() => {
          setTimeout(() => {
            this.withPhone
              ? this.getUseCouponsWithPhone()
              : this.getUseCoupons();
          }, 0);
        });
      }
    },
    getParameter: function() {
      var self = this;
      var u = navigator.userAgent,
        app = navigator.appVersion;
      var isAndroid = u.indexOf("Android") > -1 || u.indexOf("Linux") > -1; //g
      var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
      const win = window;
      var obj = {
        action: "getParameter",
        content: {
          method: "setUserInfo",
          Parameter: {}
        }
      };
      if (isAndroid) {
        App.onAppResponse(JSON.stringify(obj));
      }
      if (isIOS) {
        win.webkit.messageHandlers.onAppResponse.postMessage(
          JSON.stringify(obj)
        );
      }
    },
    // 使用优惠劵
    toUse(coupon) {
      let { url_type, url_text } = coupon;
      let { from1 } = this.$route.query;
      if (from1 != "app") {
        url_text = url_text.replace("from1=app", "");
      }
      window.location.href = url_text;
    },
    // 去领劵中心
    getMoreCoupon() {
      const { from1, phone } = this.$route.query;
      const and = from1 ? "&" : "";
      this.$router.push(
        `/user/get_coupon?${from1 == "app" ? "from1=app" : ""}${and}phone=${
          phone ? phone : ""
        }`
      );
    },
    getUseCoupons: function() {
      let that = this;
      let params = {
        page: 0
      };
      getCouponsUser(params).then(res => {
        that.couponsList = res.data.map(item => {
          return {
            ...item,
            showInfo: false
          };
        });
        that.loading = true;
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.noPictrue {
  text-align: center;
  .text {
    font-size: 0.28rem;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.5);
  }
}
</style>
